import com.alibaba.fastjson.JSON;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by donar on 17/3/8.
 */
public class CatagoryXmlParser {


    static String siteca = "CANADA";
    static String filePathca = "/Users/donar/dev/raycloud/oversea-erp-usercenter/report.ca";
    static Set<String> catsetca = new HashSet<String>(Arrays.asList(new String[]{"3234171","110218011","677211011","2206276011","2235621011","2242990011","2356393011","2972706011","3006903011","3561347011","3561350011","6205512011","6205178011","8604904011","6205518011","6967216011","6948390011","9674384011","6205506011","6205125011","6386372011","6916845011","8604916011","6291628011","6299024011","9230167011","11076214011"}));
    static String siteus = "USA";
    static String filePathus = "/Users/donar/dev/raycloud/oversea-erp-usercenter/report.us";
    static Set<String> catsetus = new HashSet<String>(Arrays.asList(new String[]{"468240", "491286", "493964", "1063498", "1084128", "3375301", "11846801", "15690151", "16310161", "16310211", "165795011", "165797011", "2335753011", "2617942011", "2619526011", "2619534011", "3238155011", "7141124011"}));
    static String sitemx = "MEXICO";
    static String filePathmx = "/Users/donar/dev/raycloud/oversea-erp-usercenter/report.mx";
    static Set<String> catsetmx = new HashSet<String>(Arrays.asList(new String[]{"9482641011", "6446440011", "11260443011", "9482611011", "9482621011", "9482671011", "9482691011", "11076224011", "9482651011", "9482594011", "9482631011", "9298577011", "11782337011", "9482661011", "9482559011", "9482681011", "9673845011"}));

    static Connection connection = JdbcUtil.getConnection();

    public static void main(String[] args) {
//        parse(siteus, filePathus, catsetus);
//        setRoot(catsetus);
//        parse(siteca, filePathca, catsetca);
//        setRoot(catsetca);
//        parse(sitemx, filePathmx, catsetmx);
//        setRoot(catsetmx);
        DocumentFactory factory = DocumentFactory.getInstance();
        Element e = factory.createElement("donar");
        Attribute attr = factory.createAttribute(e,"hello","rt");
        e.add(attr);
        System.out.println(e.asXML());


    }

    public static void parse(String site, String filePath, Set<String> catset) {
        //loadTranslate();
        long start = System.currentTimeMillis();
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(filePath);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element element = document.getRootElement();//Result
        List<Element> nodes = element.elements();
        //开始解析node
        List<String> words = new ArrayList<String>();
        for (Element node : nodes) {
            //System.out.println(i++);
            Catagory catagory = new Catagory();
            //catagoryId
            String catagoryId = node.element("browseNodeId").getText();
            //   if (!catset.contains(catagoryId))continue;
            catagory.setCatagoryId(catagoryId);
            Element browseNodeAttributes = node.element("browseNodeAttributes");
            Integer attributeCount = Integer.parseInt(browseNodeAttributes.attributeValue("count"));
            //解析属性
            if (attributeCount > 0) {
                List<Element> attrs = browseNodeAttributes.elements();
                for (Element attr : attrs) {
                    catagory.getAttributes().put(attr.attributeValue("name"), attr.getText());
                }
            }
            catagory.setName(node.elementText("browseNodeName"));
            if (catagory.getName().equals("Departments")) catagory.setName("Categories");
            catagory.setStoreContextName(node.elementText("browseNodeStoreContextName"));
            catagory.setIdPath(node.elementText("browsePathById"));
            //"11055981","3760931","11965861"
            //System.out.println(catagory.getIdPath());
            if (!inDXMCatalog(catagory.getIdPath(), catset)) continue;
            //System.out.println("GO");

            catagory.setNamePath(node.elementText("browsePathByName"));
            catagory.setHasChildren(Boolean.parseBoolean(node.elementText("hasChildren")));
            Element childIDs = node.element("childNodes");
            Integer childCount = Integer.parseInt(childIDs.attributeValue("count"));
            if (childCount > 0) {
                List<Element> cids = childIDs.elements();
                for (Element id : cids) {
                    catagory.getChildIds().add(id.getText());
                }
            }
            catagory.setProductTypeDefinitions(node.elementText("productTypeDefinitions"));
            //解析细致属性
            Element refinementsInformation = node.element("refinementsInformation");
            Integer refinementsInformationCount = Integer.parseInt(refinementsInformation.attributeValue("count"));
            if (refinementsInformationCount > 0) {
                List<Element> refinementNames = refinementsInformation.elements();
                for (Element refinementName : refinementNames) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    String name = refinementName.attributeValue("name");
                    List<Map<String, String>> fieldList = new ArrayList<Map<String, String>>();
                    List<Element> fields = refinementName.elements();
                    for (Element f : fields) {
                        Map<String, String> m = new HashMap<String, String>();
                        m.put("acceptedValues", f.elementText("acceptedValues"));
                        m.put("hasModifier", f.elementText("hasModifier"));
                        m.put("refinementAttribute", f.elementText("refinementAttribute"));
                        m.put("modifiers", f.elementText("modifiers"));
                        fieldList.add(m);
                    }
                    map.put(name, fieldList);
                    catagory.getRefinementsInformation().add(map);
                }

            }
            words.add(catagory.getName());
            insertCatagory(catagory, site);
        }
        long end = System.currentTimeMillis();

    }

    private static boolean inDXMCatalog(String idPath, Set<String> catset) {
        for (String cat : catset) {
            if (idPath.contains(cat)) return true;
        }
        return false;
    }

    static int count = 0;

    private static void insertCatagory(Catagory catagory, String site) {
        try {
            PreparedStatement pstmt = connection.prepareStatement("INSERT INTO `amazon_catagory` (catagory_id,name,store_context_name,id_path,name_path,child_ids,has_children,productTypeDefinitions,refinementsInformation,attributes,root,parent_id_path,site) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            pstmt.setString(1, catagory.getCatagoryId());
            pstmt.setString(2, catagory.getName());
            pstmt.setString(3, catagory.getStoreContextName());
            pstmt.setString(4, catagory.getIdPath());
            pstmt.setString(5, catagory.getNamePath());
            pstmt.setString(6, JSON.toJSONString(catagory.getChildIds()));
            pstmt.setBoolean(7, catagory.getHasChildren());
            pstmt.setString(8, catagory.getProductTypeDefinitions());
            pstmt.setString(9, JSON.toJSONString(catagory.getRefinementsInformation()));
            pstmt.setString(10, JSON.toJSONString(catagory.getAttributes()));
            pstmt.setBoolean(11, false);
            String parentId;
            String[] pids = catagory.getIdPath().split(",");
            if (pids.length > 1) parentId = catagory.getIdPath().substring(0, catagory.getIdPath().lastIndexOf(","));
            else parentId = "";
            pstmt.setString(12, parentId);
            pstmt.setString(13, site);
            pstmt.execute();
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println(catagory.getCatagoryId());
        }

        //System.out.println(JSON.toJSONString(catagory));
    }

    public static void setRoot(Set<String> root) {
        try {
            for (String id : root) {
                PreparedStatement pstmt = connection.prepareStatement("UPDATE `amazon_catagory` set root=1 WHERE catagory_id = ?");
                pstmt.setString(1, id);
                pstmt.execute();
                pstmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
